package com.tensquare.friend.controller;

import com.tensquare.friend.entity.Friend;
import com.tensquare.friend.service.FriendService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/friend")
@CrossOrigin
public class FriendController {
    @Autowired
    private FriendService friendService;
    @Autowired
    private HttpServletRequest request;
    /**
     *
     * @param friendid
     * @param type 1喜欢 0不喜欢
     * @return
     */
    @RequestMapping(value="/like/{friendid}/{type}",method=RequestMethod.GET)
    public Result addFriend(@PathVariable String friendid , @PathVariable String type){
        Claims claims = (Claims)request.getAttribute("user_claims");
        System.out.println("当前用户的id"+claims.getId());
        if(claims==null){
            return new Result(false, StatusCode.ACCESSERROR,"无权访问");
        }
        if (type.equals("1"))
        {
            if(friendService.addFriend(claims.getId(),friendid)==0){
                return new Result(false, StatusCode.REPERROR,"已经添加此好友");
            }
        }else {
            friendService.addNoFriend(claims.getId(),friendid);//向不喜欢列表中添加记录
        }
        return new Result(true, StatusCode.OK, "操作成功");
    }
    /**
     * 删除好友
     * @param friendid
     * @return
     */
    @RequestMapping(value="/{friendid}",method=RequestMethod.DELETE)
    public Result remove(@PathVariable String friendid){
        Claims claims=(Claims)request.getAttribute("user_claims");
        if(claims==null){
            return new Result(false, StatusCode.ACCESSERROR,"无权访问");
        }
        friendService.deleteFriend(claims.getId(), friendid);
        return new Result(true, StatusCode.OK, "删除成功");
    }

    @RequestMapping(value = "/findByUserid/{userid}",method = RequestMethod.GET)
    public List<String> findByUserid(@PathVariable String userid){
        List<Friend> friendList = friendService.findByUserid(userid);
        List<String> friendid = new ArrayList();
        for(Friend friend : friendList){
            friendid.add(friend.getFriendid());
        }
        return friendid;
    }
}
